package com.flyduck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyduck.common.exception.BusinessException;
import com.flyduck.constant.RedisConstant;
import com.flyduck.entity.SysUser;
import com.flyduck.mapper.SysUserMapper;
import com.flyduck.service.AuthService;
import com.flyduck.utils.RedisUtils;
import com.flyduck.vo.CaptchaCreateRespVO;
import com.flyduck.vo.UserInfoRespVO;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 * AuthServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2024-05-28
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private Producer producer;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public CaptchaCreateRespVO createCaptcha() {
        //redis的key
        String uuid = UUID.randomUUID().toString();
        //redis的value
        String code = producer.createText();

        log.info("uuid={},code={}",uuid,code);

        //生成验证码图片
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            throw new BusinessException("验证码生成失败",e);
        }
        BASE64Encoder encoder = new BASE64Encoder();
        String captchaImg = "data:image/jpeg;base64," + encoder.encode(outputStream.toByteArray());

        //存储到redis里面
        redisUtils.hset(RedisConstant.LOGIN_CAPTCHA_KEY,
                uuid,
                code,
                RedisConstant.LOGIN_CAPTCHA_EXPIRE);

        CaptchaCreateRespVO captchaCreateRespVO = new CaptchaCreateRespVO();
        captchaCreateRespVO.setUuid(uuid);
        captchaCreateRespVO.setCaptchaImg(captchaImg);
        return captchaCreateRespVO;
    }

    @Override
    public UserInfoRespVO getUserInfoByUserName(String username) {
        SysUser sysUser = sysUserMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, username)
        );

        UserInfoRespVO userInfoRespVO = new UserInfoRespVO();
        userInfoRespVO.setId(sysUser.getId());
        userInfoRespVO.setUsername(sysUser.getUsername());
        userInfoRespVO.setAvatar(sysUser.getAvatar());
        userInfoRespVO.setCreated(sysUser.getCreated());
        return userInfoRespVO;
    }
}
